package com.zjc.code.algorithm.my;

/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-07-23  09:03
 */
public class Code01_Binary {
    /**
     * 打印二进制数
     *
     * @param num 输入的数
     */
    public static void print(int num) {
        int count = 0;// 统计位数, 用于每隔4位打印空格
        for (int i = 31; i >= 0; i--, count++) {
            if (count == 4) {
                count = 0;
                System.out.print(" ");
            }
            System.out.print((num & (1 << i)) == 0 ? "0" : "1");
        }
        System.out.println();
    }

    public static void println() {
        for (int i = 0; i < 16; i++) {
            System.out.print("-");
        }
        System.out.println();
    }


    public static void main(String[] args) {
        int num = 1;
        // 左移, 结果相当于*2
        System.out.println("左移:");
        print(num);// 0000 1010
        print(num << 1);// 0001 0100
//        print(num * 2);// 0001 0100
        print(num << 2);// 0101 0000
        println();
        // 整型最值
        int maxInt = Integer.MAX_VALUE;
        int minInt = Integer.MIN_VALUE;
        System.out.println("MaxInt:" + maxInt);// 2^31-1
        print(maxInt);
        System.out.println("MinInt:" + minInt);// -2^31
        print(minInt);
        println();

        // 负数取反+1
        System.out.println("补码(负数取反+1):");
        int num2 = -5;
        System.out.println("原数");
        print(num2);
        System.out.println("最高位为1,说明是负数");
        System.out.println("先取反");
        print(~num2);
        System.out.println("再+1");
        print(~num2 + 1);
        System.out.println("说明是-" + (~num2 + 1));
        println();
        // 位运算
        int a = 10, b = -17;
        System.out.println("位运算:");
        System.out.println("a");
        print(a);
        System.out.println("b");
        print(b);
        System.out.println("a & b");
        print(a & b);
        System.out.println("a | b");
        print(a | b);
        System.out.println("a ^ b");
        print(a ^ b);
        System.out.println("~a");
        print(~a);
        System.out.println("~b");
        print(~b);
        println();
        // 加法
        int add = add(a, b);
        System.out.println("加法:" + add);

        // 逻辑右移与符号右移
        System.out.println("原数:" + b);
        print(b);
        System.out.println("逻辑右移:" + (b >>> 1));
        print(b >>> 1);
        System.out.println("符号右移:" + (b >> 1));
        print(b >> 1);

    }

    public static int add(int a, int b) {
        while (b != 0) {
            int carry = (a & b) << 1;
            a = a ^ b; // 非进位加法
            b = carry; // 更新进位
        }
        return a;
    }


    /**
     * 得到补码
     */
    public static int getComplement(int num) {
        if (num < 0) {
            return ~num + 1;
        }
        return num;
    }

}
